package hyperlinky;

import com.google.wave.api.*;
import java.util.*;

@SuppressWarnings("serial")
public class HyperLinkyServlet extends AbstractRobotServlet {

	Triggers triggers = new Triggers();

	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();

		if (bundle.wasSelfAdded()) {
			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView.append("Hi there, I'm HyperLinky! Click my button on the toolbar.");
		}
        
		for (Event e: bundle.getEvents()) {
			if(e.getType() == EventType.BLIP_SUBMITTED) {
				Blip theBlip = e.getBlip();
				String modBy = e.getModifiedBy();
				if(!modBy.equals("hyperlinky@appspot.com") && !modBy.equals("panda@a.gwave.com") && !modBy.equals("spelly@a.gwave.com")) {
					// textView.append("This has been edited by "  +modBy);
					processBlip(theBlip, wavelet);
				}
			}
		}
	}
		
	private void processBlip(Blip blip, Wavelet wavelet){
		TextView doc = blip.getDocument();
		String text = doc.getText();	//content of the blip
		//Locate every Annotated range
		List<Annotation> annotations = doc.getAnnotations("robot.hyperlinky.request");
		//annotations.getValue() returns which engine to use
		doc.deleteAnnotations("robot.hyperlinky.request");
		for(Annotation current : annotations) {
			String link = makeLinky(text.substring(current.getRange().getStart(), current.getRange().getEnd()), current.getValue());
			doc.setAnnotation(current.getRange(), "link/manual", link);
		}
	}
	
	private String makeLinky(String text, String value) {
		for (Trigger current : triggers.triggerList) {
			if(current.getValue().equals(value)) {
				return String.format(current.getURL(), text);
			}
		}
		return null;
		
	}
}
